package com.example.demo.controller;


import com.example.demo.mapper.MessageMapper;
import com.example.demo.mapper.MessageSessionMapper;
import com.example.demo.model.Friend;
import com.example.demo.model.MessageSession;
import com.example.demo.model.MessageSessionUserItem;
import com.example.demo.model.User;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.ls.LSException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
public class MessageSessionController {

    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private static Logger log = LoggerFactory.getLogger(FriendController.class);


    //展示会话列表
    @RequestMapping("/sessionList")
    public Object getMessageSessionList(HttpServletRequest request)
    {
        List<MessageSession> messageSessionList = new ArrayList<>();
        //1.获取到当前用户的 userId(从HttpServletRequest中获取)
        User user = (User)request.getSession().getAttribute("user");
        Integer userId = user.getUserId();

        //2.根据 userId 查询数据库获取当前usrId在哪些会话中出现过
        List<Integer> sessionIds = messageSessionMapper.getSessionIdsByUserId(userId);

        //3.遍历会话Id,查询每个会话中有哪些好友出现过
        for(int i = 0; i < sessionIds.size(); ++i)
        {
            Integer sessionId = sessionIds.get(i);
            List<Friend> friends =  messageSessionMapper.getFriendsBySessionId(sessionId,userId);

            //4.遍历会话Id,查询初每个会话的最后一条消息 也可能查不到消息,因为新创建的会话可能还没有发过消息
            //String lastMessage = String.valueOf(messageSessionMapper.getFriendsBySessionId(sessionId,userId));
            String lastMessage = messageMapper.getLastMessageBySessionId(sessionId);
            if(lastMessage == null) {
                lastMessage = "";
            }

            //System.out.println( "userId:" + userId + " 接收到的lastMessage是:" + lastMessage);

            //5.构造出 MessageSession 对象
            MessageSession messageSession = new MessageSession(sessionId,friends,lastMessage);

            messageSessionList.add(messageSession);
        }

        return messageSessionList;
    }

    //新增会话,将会话加入到数据库 并且 将聊天的两个人加入到数据库
    @RequestMapping("/session")
    @Transactional //开启事务,保证此方法执行的原子性
    public Object addMessageSession(Integer toUserId,HttpServletRequest request)
    {
        User user = (User)request.getSession().getAttribute("user");
        Integer userId = user.getUserId();

        //进行数据库的插入操作
        //1.先给 message_session(会话表)插入数据
        // MessageSession
        MessageSession messageSession = new MessageSession();
        messageSessionMapper.addMessageSession(messageSession);

        //给 message_session_user表 插入两条数据即聊天的两个人的userId 和 sessionId
        MessageSessionUserItem item1 = new MessageSessionUserItem();
        item1.setSessionId(messageSession.getSessionId()); //因为useGeneratedKeys="true" keyProperty="sessionId"设置了将sessionId添加到这个类对应的对象中
        item1.setUserId(userId);

        MessageSessionUserItem item2 = new MessageSessionUserItem();
        item2.setUserId(toUserId);
        item2.setSessionId(messageSession.getSessionId());
        messageSessionMapper.addMessageSessionUser(item1);
        messageSessionMapper.addMessageSessionUser(item2);

        log.info("新增会话成功! sessionId=" + messageSession.getSessionId() + " userId1=" + item1.getUserId() + " userId2=" + item2.getUserId());

        HashMap<String,Integer> resp = new HashMap<>();
        resp.put("sessionId", messageSession.getSessionId());
        return  resp;
    }

}
